<?php

class WSB_Hooks
{

	/**
	 * @var WSB_Hooks
	 */
	private static $_instance;

    /**
     * @var array
     */
    private $_hooks = array();

    /**
     * Singleton
     */
    private function __construct()
    {}

    /**
     * Singleton
     */
    private function __clone()
    {}

	/**
	 * @return WSB_Hooks
	 */
	public static function instance()
	{
		if(is_null(self::$_instance)) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * @param array $hooks
	 */
	public function addHooks(array $hooks)
	{
        foreach($hooks AS $hook) {
            $this->addHook($hook);
        }
	}

	/**
	 * @param array $hook
	 */
	public function addHook(array $hook)
	{
	    $this->_hooks[] = $hook;
	}

    /**
     * @param string $hookKey
     * @param WSB_Xtension_View $view
     * @return string
     */
    public function render($hookKey, WSB_Xtension_View $view)
    {
        $content = '';
        foreach($this->_hooks AS $hook) {
            if(isset($hook['key']) && ($hookKey === $hook['key'])) {
                if(!empty($hook['path']) && !empty($hook['class']) && !empty($hook['method'])) {
                    $path = $hook['path'];
                    require_once($path);
                    $class = $hook['class'];
                    $method = $hook['method'];
                    $hookObj = new $class();
                    $content .= $hookObj->$method($view);
                }
            }
        }
        return $content;
    }

    /**
     * @param string $hookKey
     * @param mixed $content
     * @param object $obj
     */
    public function execute($hookKey, &$content, &$obj)
    {
        foreach($this->_hooks AS $hook) {
            if(isset($hook['key']) && ($hookKey === $hook['key'])) {
                if(!empty($hook['path']) && !empty($hook['class']) && !empty($hook['method'])) {
                    $path = $hook['path'];
                    require_once($path);
                    $class = $hook['class'];
                    $method = $hook['method'];
                    $hookObj = new $class();
                    $hookObj->$method($content, $obj);
                }
            }
        }
    }

    /**
     * @param string $hookKey
     * @return boolean
     */
    public function hasKey($hookKey)
    {
        foreach($this->_hooks AS $hook) {
            if(isset($hook['key']) && ($hookKey === $hook['key'])) {
                return true;
            }
        }
        return false;
    }

}